<template>
    <a-form :model="form" ref="formRef" :rules="formRules" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-item :label="$t('main.account')" name="account">
            <a-input v-model:value="form.account" :maxlength="50" disabled />
        </a-form-item>
        <a-form-item :label="$t('main.displayName')" name="displayName">
            <a-input v-model:value="form.displayName" :maxlength="50" />
        </a-form-item>
        <a-form-item :label="$t('main.sex')" name="sex">
            <a-select v-model:value="form.sex" ref="select">
                <a-select-option v-for="item in genders" :key="item.gender" :value="item.gender">{{ item.displayName
                }}</a-select-option>
            </a-select>
        </a-form-item>
        <a-form-item :label="$t('main.description')" name="description">
            <a-textarea v-model:value="form.description" autoSize :maxlength="255" showCount />
        </a-form-item>
    </a-form>
</template>

<script setup lang='ts'>
import i18n from '@/i18n';
import cache from '@/utils/cache';
import { UserDto, UserResultDto } from '@/models/user';
import { message, type FormInstance } from 'ant-design-vue';
import { reactive, ref, type Ref } from 'vue';
import type { Rule } from 'ant-design-vue/lib/form';
import { updateUserApi } from '@/services/main';

defineExpose({ ok });

const form: UserDto = reactive<UserDto>(cache.getUserInfo() ?? new UserDto);
const formRef: Ref<FormInstance | undefined> = ref<FormInstance>();
const formRules: Record<string, Rule[]> = {
    displayName: [
        {
            required: true,
            max: 50,
            message: i18n.global.t("main.required.displayName"),
            trigger: "blur",
        },
    ],
};
const genders = [
    {
        gender: 0,
        displayName: i18n.global.t("main.unknown"), //未知
    },
    {
        gender: 1,
        displayName: i18n.global.t("main.male"), //男
    },
    {
        gender: 2,
        displayName: i18n.global.t("main.female"), //女
    }
]

async function ok(): Promise<boolean> {
    try {
        await formRef.value?.validate();
        const response: UserResultDto = await updateUserApi(form);
        cache.setUserInfo(response);
        message.success(i18n.global.t("main.required.modifySuccess"));
        return true;
    } catch {
        return false;
    }
}
</script>